define([
		'yf', 'yfUtil',
		'jquery',
		'underscore',
		'./common',
		'text!./template/list.html',
		'text!./template/bottom.html',
		'text!./template/bottomDetailList.html',
		'Layer',
		'myParabola',
		'IScroll'
	],
	function(yf, yfUtil, $, _, common, listTpl, bottomTpl, bottomDetailTpl, Layer, Parabola,IScroll) {
		var me, shoppingCarData, mylayer,myAnimate=true;
		var main = {
			initialize: function() {
				me = main;
				common.init(); //生成顶部商家信息
				this.render();
			},
			bindEvents: {
				'click .classList': 'transClass',
				"click .addOneBtn": 'reRenderProList',
				"click .reduceBtn": 'reRenderProList',
				"click .bottomDetails": "showBottom",
				"click .bottomDetailsAddBtn": "renderBottomDetails",
				"click .bottomDetailsReduceBtn": "renderBottomDetails"
			},
			//生成侧边栏和物品列表
			render: function() {
				var url = './data/shoppingList.json';
				yf.ajax({
					type: "get",
					url: url,
					async: true,
					success: function(data) {
						var data = data.data;
						var classListTpl = "",
							productListTpl = "";
						var html = $(listTpl).html();
						var fn = _.template(html);
						for(var i = 0; i < data.length; i++) {
							classListTpl += '<div class="classList" data-id="' + data[i].class.id + '">';
							classListTpl += data[i].class.name;
							classListTpl += '</div>';
							productListTpl += '<a href="' + data[i].class.id + '"></a>';
							productListTpl += '<div class="' + data[i].class.id + " title" +'">' + data[i].class.name + '</div>';
							for(var j = 0; j < data[i].list.length; j++) {
								var item = data[i].list[j];
								var tpl = fn({
									item: item
								});
								productListTpl += tpl;
							}
						}
						$('.slide').html(classListTpl);
						$('.content').html(productListTpl);
						//把最后一个list顶高,避免被遮挡
						me.$el.find('.productList:last').css('margin-bottom', '50px');
						//等列表加载完了再渲染
						me.renderShoppingCar();
						//图片懒加载
						var myLazyLoad = new LazyLoad(me.$el.find('.content'),me.$el.find('.proImgDiv img'));
						myLazyLoad.init();
						//点击侧边栏第一个
						me.$el.find('.classList').eq(0).click();
					}
				});
			},
			//获取购物车的数据
			renderShoppingCar: function() {
				var url = './data/shoppingCarData.json';
				yf.ajax({
					type: "get",
					url: url,
					async: true,
					success: function(data) {
						shoppingCarData = data.data;
						//渲染购物车底座
						me.reRenderBottom(shoppingCarData);
						//渲染商品列表加减号
						me.renderListNumAndReduceBtn(shoppingCarData);
					}
				});
			},
			//把有购物车数量的货物的减号和加号显示出来
			renderListNumAndReduceBtn: function(shoppingCarData) {
				for(var i = 0; i < shoppingCarData.length; i++) {
					var id = shoppingCarData[i].id;
					var buyNum = shoppingCarData[i].buyNum;
					var proList = $('.productList[data-id="' + id + '"]');
					proList.find('.reduceBtn').removeClass('displayNone');
					proList.find('.bynNumSPAN').removeClass('displayNone').html(buyNum);
				}
			},
			//滚动内容区到固定位置
			transClass: function(e) {
				var target = $(e.currentTarget);
				me.$el.find('.classList').removeClass('active');
				target.addClass('active');
				var id = target.attr('data-id');
				var ProlistTitle = me.$el.find('.' + id); //右侧类别标题元素
				//offsetTop是js专用，用于获取到父元素最顶层的距离
				//jq应该用offset.top()；但是这是到document的距离
				var top = ProlistTitle[0].offsetTop;
				//scrollTop就是滚动到离父元素的顶部距离
				me.$el.find('.content').animate({
					"scrollTop": top
				});
			},
			//点击加减号的显示隐藏判断
			reRenderProList: function(e) {
				var target = $(e.currentTarget);
				var productList = target.closest('.productList');
				var name = productList.attr('data-name');
				var price = productList.attr('data-price');
				var id = productList.attr('data-id');
				var buyNum = parseInt(productList.find('.bynNumSPAN').html());
				var reduceBtn = productList.find('.reduceBtn');
				var buyNumSPAN = productList.find('.bynNumSPAN');
				//如果点的是加号并且购买数为0，就要多一步数组push
				//如果点的是减号并且购买数为1，就要多一步数组remove
				if(target.hasClass('addOneBtn') == true) {
					if(buyNum == 0) {
						reduceBtn.removeClass('displayNone');
						buyNumSPAN.removeClass('displayNone');
						buyNum += 1;
						var obj = {
							id: id,
							name: name,
							price: price,
							buyNum: buyNum
						}
						shoppingCarData.push(obj);
					} else {
						buyNum += 1;
						//更新购物车数据
						for(var i = 0; i < shoppingCarData.length; i++) {
							var item = shoppingCarData[i];
							if(item.id == id) {
								item.buyNum = buyNum;
							}
						}
					}
					//购物车动画
					if($('.myLayer').length==0) {
						var goalTarget = me.$el.find('.bottomDetailsNumber');
						var bool = new Parabola({
							startEl: target,
							endEl: goalTarget,
							speed: 'normal',
							callback: function() {
								if(myAnimate){
									myAnimate = false;
								var bottomDetailsNumber = me.$el.find('.bottomDetailsNumber');
								var fontSize = bottomDetailsNumber.css('font-size');
								var bigfontSize = parseInt(fontSize)+22+'px';
							 	bottomDetailsNumber.animate({
									"fontSize": bigfontSize
								},"fast",function(){
									bottomDetailsNumber.animate({
										"fontSize": fontSize
									},"fast",function(){
										myAnimate = true;
									});
								});
								}
							}
						});
						bool.run();
					}
				}
				if(target.hasClass('reduceBtn') == true) {
					if(buyNum == 1) {
						reduceBtn.addClass('displayNone');
						buyNumSPAN.addClass('displayNone');
						buyNum -= 1;
						//删除数组
						Array.prototype.removeByValue = function(val) {
								for(var i = 0; i < this.length; i++) {
									if(this[i] == val) {
										this.splice(i, 1);
										break;
									}
								}
							}
							//更新购物车数据
						for(var i = 0; i < shoppingCarData.length; i++) {
							var item = shoppingCarData[i];
							if(item.id == id) {
								//item.buyNum = buyNum;
								shoppingCarData.removeByValue(item);
							}
						}
					} else {
						buyNum -= 1;
						//更新购物车数据
						for(var i = 0; i < shoppingCarData.length; i++) {
							var item = shoppingCarData[i];
							if(item.id == id) {
								item.buyNum = buyNum;
							}
						}
					}
				}
				buyNumSPAN.html(buyNum);
				me.reRenderBottom(shoppingCarData);
			},
			reRenderBottom: function(shoppingCarData) {
				//计算总共有几份
				//计算每份*单价为总价
				//计算够不够起送，不够的话还差多少钱
				var number = 0;
				var sum = 0;
				var mini = localStorage.getItem('miniSend'); //最低起送
				var sendMoney = localStorage.getItem('sendMoney'); //配送费
				//假设数据
				mini = 200;
				sendMoney = 5;
				var defferen = 0; //差价
				var text = "";
				for(var i = 0; i < shoppingCarData.length; i++) {
					var item = shoppingCarData[i];
					number += parseInt(item.buyNum);
					sum += (parseInt(item.buyNum) * parseInt(item.price));
				}
				if(sum < mini) {
					defferen = mini - sum;
					text = "差¥" + defferen + "起送";
				} else {
					text = "去结算";
				}
				var obj = {
					number: number,
					sum: sum,
					text: text,
					sendMoney: sendMoney
				}
				//如果为空，就是第一次加载
				if(me.$el.find('.bottom').html() == "") {
					var html = $(bottomTpl).html();
					var fn = _.template(html);
					var tpl = fn({
						result: obj
					});
					me.$el.find('.bottom').html(tpl);
					//不为空，直接改变内容
				} else {
					var iconClass = "";
					if(obj.number == 0) {
						iconClass = "gray";
						obj.number = "没点噢";
						me.$el.find('.bottomDetailsNumber').removeClass("yellow");
						me.$el.find('.bottomDetailsNumber').addClass("gray");
					} else {
						iconClass = "yellow";
						me.$el.find('.bottomDetailsNumber').removeClass("gray");
						me.$el.find('.bottomDetailsNumber').addClass("yellow");
					}
					me.$el.find('.bottomDetailsNumber').html(obj.number);
					me.$el.find('.bottomDetailsSum').html("¥" + obj.sum);
					me.$el.find('.bottomDetailsSendMoney').html('另需配送费¥' + obj.sendMoney);
					me.$el.find('.bottomDetailsText').html(obj.text);
				}
			},
			showBottom: function() {
				var html = $(bottomDetailTpl).html();
				var fn = _.template(html);
				var tpl = fn({
					result: shoppingCarData
				});
				var topDetails = $('.bottom .topDetails');
				if(topDetails.hasClass('displayNone') && shoppingCarData.length != 0) {
					topDetails.html(tpl).removeClass('displayNone');
					//弹层
					var showlist = [];
					showlist.push(me.$el.find('.bottom'));
					mylayer = new Layer($('body'), showlist, function() {
						//回调，就是点击弹层除了消失还会执行什么操作
						topDetails.html("").addClass('displayNone');
					});
				} else {
					topDetails.html("").addClass('displayNone');
					mylayer.remove();
				}
			},
			renderBottomDetails: function(e) {
				var target = $(e.currentTarget);
				var bottomDetailsList = target.closest('.bottomDetailsList');
				var buyNum = parseInt(bottomDetailsList.find('.bottomDetailsBuyNum').html());
				var price = parseInt(bottomDetailsList.attr('data-price'));
				console.log(price);
				//找出商品列表中对应的列
				var id = bottomDetailsList.attr('data-id');
				var proList = $('.productList[data-id="' + id + '"]');
				//取消冒泡，不然父元素也会触发点击事件
				e.stopPropagation();
				//点击加号
				if(target.hasClass('bottomDetailsAddBtn')) {
					buyNum += 1;
					var singleSum = price * buyNum;
					bottomDetailsList.find('.bottomDetailsBuyNum').html(buyNum);
					bottomDetailsList.find('.bottomDetailsOneSum').html("¥" + singleSum);
					//商品列表对应列也点击加号
					proList.find('.addOneBtn').click();
				} else {
					//如果为1了还点减号，就删除这一条
					if(parseInt(buyNum) == 1) {
						bottomDetailsList.remove();
					} else {
						buyNum -= 1;
						var singleSum = price * buyNum;
						bottomDetailsList.find('.bottomDetailsBuyNum').html(buyNum);
						bottomDetailsList.find('.bottomDetailsOneSum').html("¥" + singleSum);
					}
					//商品列表对应列也点击减号
					proList.find('.reduceBtn').click();
					if(shoppingCarData.length == 0) {
						mylayer.remove();
					}
				}
			}
		}
		return main;
	});